package ar.edu.itba.it.poo

// TODO: Se tiene el mismo problema que en la clase Complex: es necesario hacer el import explícito para que la conversión implícita esté en el scope.
object Rational {
    implicit def intToRational(number: Int) = new Rational(number)
}

class Rational(val n: Int, val d: Int) {
    require(d != 0)

    private val g = gcd(n, d)
    val numerator: Int = n / g
    val denominator: Int = d / g

    def this(n: Int) = this(n, 1)

    def +(that: Rational) = new Rational(numerator * that.denominator + that.numerator * denominator, numerator * denominator)
    def -(that: Rational) = new Rational(numerator * that.denominator - that.numerator * denominator, numerator * denominator)
    def *(that: Rational) = new Rational(numerator * that.numerator, denominator * that.denominator)

    override def toString = numerator + "/" + denominator

    private def gcd(a: Int, b: Int): Int = {
        if (b == 0) a else gcd(b, a % b)
    }
}

object RationalTest extends Application {

    import ar.edu.itba.it.poo.Rational._

    val n1 = new Rational(-1, 2)
    val n2 = new Rational(5)

    println("n1: " + n1)
    println("n2: " + n2)
    println("n1 + n2: " + (n1 + n2))
    println("n1 * n2: " + (n1 * n2))

    val n3 = n1 + 5
    println("n1 + 5: " + n3)
}